package com.ruyuan.engine.service;
import com.ruyuan.engine.pojo.RuleComplexParam;
import com.ruyuan.engine.pojo.RuleEventExecuteParam;
import com.ruyuan.engine.utils.ClickHouseUtils;
import com.ruyuan.engine.utils.CombinationServiceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class CombinationRuleServiceClickHouseManagerImpl implements CombinationRuleService {

    protected static final Logger log = LoggerFactory.getLogger(CombinationRuleServiceClickHouseManagerImpl.class);


    private static Connection connection;
    static {
        try {
            connection = ClickHouseUtils.getConnection();
        }catch (Exception e) {
            e.printStackTrace();
            log.error("clickHouse 初始化失败");

        }
    }

    @Override
    public boolean mathRuleConditionCount(String userId, RuleComplexParam ruleComplexParam) {
        List<RuleEventExecuteParam> combinationRuleParams = ruleComplexParam.getCombinationRuleParams();

        for (RuleEventExecuteParam ruleEventExecuteParam:combinationRuleParams) {
            //匹配方法
            Boolean isMatch = matchClientLogAndCombinationRuleParams(userId, ruleEventExecuteParam);
            if (!isMatch) return false;
        }
        //组合的规则都满足条件
        return true;
    }

    @Override
    public boolean mathRuleConditionCount(RuleComplexParam ruleComplexParam) {
        return mathRuleConditionCount(null,ruleComplexParam);
    }

    @Override
    public boolean mathRuleConditionCount(String userId, RuleEventExecuteParam ruleEventExecuteParam) {
        return matchClientLogAndCombinationRuleParams(userId,ruleEventExecuteParam);
    }

    @Override
    public boolean mathRuleConditionCount(RuleEventExecuteParam ruleEventExecuteParam) {
        return mathRuleConditionCount(null,ruleEventExecuteParam);
    }

    private Boolean matchClientLogAndCombinationRuleParams(String userId, RuleEventExecuteParam ruleEventExecuteParam)  {
        //生成sql语句
        try {
            String sql = CombinationServiceUtils.GenSearchCombinationSql(userId, ruleEventExecuteParam);
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                String userCnt = resultSet.getString("userCnt");
                ruleEventExecuteParam.setCombinationMatchCount(ruleEventExecuteParam.getCombinationMatchCount() + Integer.parseInt(userCnt));
            }
            if (ruleEventExecuteParam.getCombinationMatchCount() < ruleEventExecuteParam.getThreshold()) {
                return false;
            }else {
                return true;
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("SQL 预编译异常");
        }
        return false;

    }
}
